// Definition for a binary tree node.
function TreeNode(val, left, right) {
  this.val = (val === undefined ? 0 : val)
  this.left = (left === undefined ? null : left)
  this.right = (right === undefined ? null : right)
}

function createTree(arr) {
  if (arr.length < 1)
    return null;
  let NodeArr = [];
  for (let i = 0; i < arr.length; i++) {
    if (arr[i] == null) {
      NodeArr.push(null);
      continue;
    }
    let tempNode = new TreeNode(arr[i], null, null);
    NodeArr.push(tempNode);
  }
  for (let i = 0; i < arr.length; i++) {
    if (NodeArr[i] == null) continue;
    if (2 * i + 1 < arr.length)
      NodeArr[i].left = NodeArr[2 * i + 1];
    if (2 * i + 2 < arr.length)
      NodeArr[i].right = NodeArr[2 * i + 2];
  }
  return NodeArr[0];
}

function preShow(node) {
  if (node == null)
    return;
  console.log(node.val);
  preShow(node.left);
  preShow(node.right);
}
/**
 * @param {TreeNode} root
 * @param {number} x
 * @param {number} y
 * @return {boolean}
 */
var isCousins = function (root, x, y) {
  root = createTree(root);
  if (!root) return false;

  let queue = [{
    node: root,
    father: null,
    depth: 1
  }];
  while (queue.length > 0) {
    const obj = queue.shift();
    const value = obj.node.val;
    // 如果既不是x也不是y
    if(value !== x && value !== y) {
      obj.node.left && queue.push({
        node: obj.node.left,
        father: obj.node,
        depth: obj.depth + 1
      });
      obj.node.right && queue.push({
        node: obj.node.right,
        father: obj.node,
        depth: obj.depth + 1
      });
      continue;
    }
    // 如果为x或者y
    for(let i = 0; i < queue.length; i++) {
      if(queue[i].node.val == (value == x ? y : x) && queue[i].father != obj.father && queue[i].depth == obj.depth) {
        return true;
      }
    }
    return false;
  }
  return false;
};
let root = [1, 2, 3, 4],
  x = 4,
  y = 3;
console.log(isCousins(root, x, y));
root = [1, 2, 3, null, 4, null, 5], x = 5, y = 4;
console.log(isCousins(root, x, y));
root = [1, 2, 3, null, 4], x = 2, y = 3;
console.log(isCousins(root, x, y));
